Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
event-source-polyfill
Advanced tools
The event-source-polyfill package provides a polyfill for the EventSource API, which is used for receiving server-sent events (SSE). This is particularly useful for environments that do not natively support EventSource, such as older browsers or certain server-side JavaScript environments.
Basic EventSource Polyfill
This code demonstrates how to use the event-source-polyfill to create an EventSource instance that listens for server-sent events from a specified URL. It sets up handlers for incoming messages and errors.
const EventSource = require('event-source-polyfill');
const es = new EventSource('http://example.com/events');
es.onmessage = function(event) {
console.log('New message:', event.data);
};
es.onerror = function(error) {
console.error('Error:', error);
};
Custom Event Handlers
This code shows how to add custom event listeners for specific event types using the event-source-polyfill. In this example, a custom event named 'customEvent' is handled.
const EventSource = require('event-source-polyfill');
const es = new EventSource('http://example.com/events');
es.addEventListener('customEvent', function(event) {
console.log('Custom event received:', event.data);
});
es.onerror = function(error) {
console.error('Error:', error);
};
Reconnection Logic
This code demonstrates how to handle reconnection logic using the event-source-polyfill. It listens for errors and attempts to reconnect if the connection is closed.
const EventSource = require('event-source-polyfill');
const es = new EventSource('http://example.com/events', { withCredentials: true });
es.onopen = function() {
console.log('Connection opened');
};
es.onmessage = function(event) {
console.log('New message:', event.data);
};
es.onerror = function(error) {
console.error('Error:', error);
if (es.readyState === EventSource.CLOSED) {
console.log('Reconnecting...');
es = new EventSource('http://example.com/events', { withCredentials: true });
}
};
The eventsource package is a pure JavaScript implementation of the EventSource client for Node.js. It provides similar functionality to event-source-polyfill but is specifically designed for server-side use in Node.js environments.
The sse package is a lightweight library for handling server-sent events in Node.js. It offers a simple API for creating and managing EventSource connections, similar to event-source-polyfill, but is more focused on server-side implementations.
The eventsource-polyfill package is another polyfill for the EventSource API, similar to event-source-polyfill. It aims to provide compatibility for environments that do not natively support EventSource, with a focus on both client-side and server-side use cases.
Пожалуйста не используйте эту обосранную библиотеку!
You can get the code from npm or bower:
npm install event-source-polyfill
bower install event-source-polyfill
Just include src/eventsource.js
or src/eventsource.min.js
in your page to use the polyfill.
Unless a typescript definition file is created for this polyfill, this is how you would use it in an Ionic2 project. It should (in theory) be very similar in an Angular2 project.
npm install event-source-polyfill
Add to (or create) src/app/polyfills.ts (path is relative to where polyfills.ts is) :
import 'path/to/event-source-polyfill/src/eventsource.min.js'
Add anywhere you need access to EventSourcePolyfill class :
declare var EventSourcePolyfill: any;
import { NativeEventSource, EventSourcePolyfill } from 'event-source-polyfill';
const EventSource = NativeEventSource || EventSourcePolyfill;
// OR: may also need to set as global property
global.EventSource = NativeEventSource || EventSourcePolyfill;
padding=true
query argument)npm install
) and then run the build (npm run build
). It should generate a new version of src/eventsource.min.js
.http://username:password@github.com
.var es = new EventSourcePolyfill('/events', {
headers: {
'X-Custom-Header': 'value'
}
});
lastEventId
var es = new EventSourcePolyfill(hubUrl, {
lastEventIdQueryParameterName: 'Last-Event-Id'
});
var PORT = 8081;
var http = require("http");
var fs = require("fs");
var url = require("url");
http.createServer(function (request, response) {
var parsedURL = url.parse(request.url, true);
var pathname = parsedURL.pathname;
if (pathname === "/events.php") {
response.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-store",
"Access-Control-Allow-Origin": "*"
});
var padding = new Array(2049);
response.write(":" + padding.join(" ") + "\n"); // 2kB padding for IE
response.write("retry: 2000\n");
var lastEventId = Number(request.headers["last-event-id"]) || Number(parsedURL.query.lastEventId) || 0;
var timeoutId = 0;
var i = lastEventId;
var c = i + 100;
var f = function () {
if (++i < c) {
response.write("id: " + i + "\n");
response.write("data: " + i + "\n\n");
timeoutId = setTimeout(f, 1000);
} else {
response.end();
}
};
f();
response.on("close", function () {
clearTimeout(timeoutId);
});
} else {
if (pathname === "/") {
pathname = "/index.html";
}
if (pathname === "/index.html" || pathname === "../src/eventsource.js") {
response.writeHead(200, {
"Content-Type": pathname === "/index.html" ? "text/html" : "text/javascript"
});
response.write(fs.readFileSync(__dirname + pathname));
}
response.end();
}
}).listen(PORT);
<?php
header("Content-Type: text/event-stream");
header("Cache-Control: no-store");
header("Access-Control-Allow-Origin: *");
$lastEventId = floatval(isset($_SERVER["HTTP_LAST_EVENT_ID"]) ? $_SERVER["HTTP_LAST_EVENT_ID"] : 0);
if ($lastEventId == 0) {
$lastEventId = floatval(isset($_GET["lastEventId"]) ? $_GET["lastEventId"] : 0);
}
echo ":" . str_repeat(" ", 2048) . "\n"; // 2 kB padding for IE
echo "retry: 2000\n";
// event-stream
$i = $lastEventId;
$c = $i + 100;
while (++$i < $c) {
echo "id: " . $i . "\n";
echo "data: " . $i . ";\n\n";
ob_flush();
flush();
sleep(1);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>EventSource example</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="../src/eventsource.js"></script>
<script>
var es = new EventSource("events.php");
var listener = function (event) {
var div = document.createElement("div");
var type = event.type;
div.appendChild(document.createTextNode(type + ": " + (type === "message" ? event.data : es.url)));
document.body.appendChild(div);
};
es.addEventListener("open", listener);
es.addEventListener("message", listener);
es.addEventListener("error", listener);
</script>
</head>
<body>
</body>
</html>
With some dynamic imports it may work in node.js:
Install the library and the dependency:
npm install @titelmedia/node-fetch
npm install event-source-polyfill
x.js:
// The @titelmedia/node-fetch is used instead of node-fetch as it supports ReadableStream Web API
import('@titelmedia/node-fetch').then(function (fetch) {
globalThis.fetch = fetch.default;
globalThis.Response = fetch.default.Response;
import('event-source-polyfill').then(function (x) {
var es = new x.default.EventSourcePolyfill('http://localhost:8004/events');
es.onerror = es.onopen = es.onmessage = function (event) {
console.log(event.type + ': ' + event.data);
};
});
});
node --experimental-modules ./x.js
The MIT License (MIT)
Copyright (c) 2012 vic99999@yandex.ru
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
A polyfill for http://www.w3.org/TR/eventsource/
The npm package event-source-polyfill receives a total of 490,728 weekly downloads. As such, event-source-polyfill popularity was classified as popular.
We found that event-source-polyfill demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.